<?php
/*
 * @Author: your name
 * @Date: 2020-06-06 09:13:05
 * @LastEditTime: 2020-06-06 09:45:26
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \hotel\application\api\controller\Order.php
 */ 
namespace app\api\controller;

use think\Controller;
use think\Db;
use think\Exception;
use org\Jdk_inc;

class Order extends Base
{
    /**
     * 微信支付生成订单
     */
    public function wxpay($data){
        
        $room_id = $data['room_id'];//获取房间id
        
        if(!$room_id) return ['code'=>0,'msg'=>"参数错误"];
        $in_time = $data['in_time'];//获取入住时间
        if(!$in_time) return ['code'=>0,'msg'=>"请选择入住时间"];
        $out_time = $data['out_time'];//获取离店时间
        if(!$out_time) return ['code'=>0,'msg'=>"请选择离店时间"];
        $go_time = $data['go_time'];//获取离店时间
        if(!$go_time) return ['code'=>0,'msg'=>"请选择到店时间"];
        $days = $data['days'];//入住时长
        $userlist = json_decode($data['userlist'],true);//获取酒店身份登记信息
        if(empty($userlist)) return ['code'=>0,'msg'=>"请输入个人信息"];
        $invoice_id = $data['invoice_id'];//发票 
        $coupon_id = $data['coupon_id'];//优惠券id 
        $hours = $data['hour'];//住房的小时数针对钟点房
        $remark = $data['remark'];//备注 
        
        
        
        //入住人数
        $innum = count($userlist);
        
        if($innum>3){
            return ['code'=>0,'msg'=>"入住人数超过限制"];
        }
        //查找房间
        $room = db('room')->where(['id'=>$room_id,'status'=>0])->find();
        
        if(empty($room)) return ['code'=>0,'msg'=>"房间已下架"];
        
        // 转化时间格式 用来找到入住的每一天的时间
        $in_date = date('Y-m-d',$in_time);
        $out_date = date('Y-m-d',$out_time);
        $arr_date = db('time')->where(['date'=>['BETWEEN',[$in_date,$out_date]]])->select();

        if($room['one_cate'] == 0){
            // 为过夜房的时候需要将选择的最后一天减去 而钟点房不需要
            array_pop($arr_date);
        }
        // 获取id
        $arr_id = array_column($arr_date, 'id');
        // 查找这段时间内的房间信息
        $arr_prices = db('room_price')->where(['room_id'=>$room_id,'time_id'=>['IN',$arr_id],'status'=>0])->order('num asc')->select();
        // 查找房间的价格和这段范围内最低的数量
        // 最低的数量用min_num表示 顺便将一间房间在这段时间内的金额计算出来赋值给$room['new_price']
        $room['new_price'] = 0;
        $min_num = 100;
        foreach ($arr_prices as $i => $item) {
            $room['new_price'] += $item['price'];
            if($item['num'] != -1 && $item['num'] < $min_num){
                $min_num = $item['num'];
            }
        }

        // 获取时间id
             
        if($innum>$min_num){
            return ['code'=>0,'msg'=>"房间数量不足,最多可定".$min_num."套"];
        }
        
        
        
         //查询用户信息
        $user = db('user')->find($this->user_id);

        //根据用户的等级查找折扣
        if($room['is_activity']==0){
            // 普通房享受正常会员折扣
            $percent = db('vip_cate')->where(['level' => $user['vip_id']])->value('percent');
        }else{
            // 活动房原价购买
            $percent = 10;
        }
        
        
        //计算支付金额
        $allmoney = $room['new_price']*$innum;
        
        $H = date('H');
        $time = time();
        //查找酒店设置的钟点房的信息
        $hotel = db('hotel')->field('start_time,end_time')->find(1);
        
        if ($room['one_cate'] == 1) { //钟点房
            if ($hotel['start_time'] > $H || $hotel['end_time'] < $H) {

                return ['code' => 0, 'msg' => "请在规定时间内预约"];
            }
             //计算会员价
            $money = $allmoney;
            $cate = 1; 
            
        }else{//过夜房
            $cate = 0; 
            //计算会员价
            $money = sprintf("%.2f", ($allmoney * $percent)/10) ;
        }
        
          
        
        if($money<=0){
            return ['code' => 0, 'msg' => "支付金额错误"];
        }
        
        if($coupon_id!=0){
            if ($room['is_coupon'] == 1) {
                
                return ['code' => 0, 'msg' => "该房间不支持优惠券"];
            }
            
            //查找优惠券
            $coupon = db('coupon_user')
                ->where(['user_id' => $this->user_id, 'id' => $coupon_id, 'status' => 0]) 
                ->find();
            
            if (empty($coupon)) {
                return ['code' => 0, 'msg' => "优惠券失效"];
            } else {
                
                $coupon_info = unserialize($coupon['coupon_info']);
               
                //满多少可用
                $full_money = $coupon_info['full_money'];
                
                if ($full_money > $money) {
                    return ['code' => 0, 'msg' => "未达到优惠券使用规则"];
                }
                
                //支付金额
                $money = $money - $coupon_info['money'];
                if ($money <= 0) {
                    return ['code' => 0, 'msg' => "支付金额错误"];
                }
            }
        
            
        }
        
        $data = [
            'order_number' => makeOrderNo(),
            'user_id' => $this->user_id,
            'room_id' => $room_id,
            'in_time' => $in_time, //入驻时间
            'out_time' => $out_time, //离店时间
            'go_time' => $go_time, //到店时间
            'days' => $days, //入驻天数
            'money' => $money,//实际下单金额
            'ordermoney' => $allmoney,//应付金额
            'addtime' => time(),
            'status' => 0, 
            'coupon_id' => $coupon_id, //优惠券id
            'type' => 0, //支付方式微信
            'userlist' => serialize($userlist),
            'invoice_id' => $invoice_id, //发票id
            'remark' => $remark, //备注
            'room_num' => $innum, //人数
            'hours' => $hours, //人数
            'cate' => $cate,
        ];
        
        db('room_price')->where(['time_id'=>['IN',$arr_id]])->setDec('num',$innum);
        db('room_price')->where(['time_id'=>['IN',$arr_id]])->setInc('use_num',$innum);
        $res = db('order')->insert($data);
        if ($res) {
            return ['code' => 1, 'msg' => "订单生成成功", 'data' => $data['order_number']];
        } else {
            return ['code' => 1, 'msg' => "订单生成失败", 'data' => $data['order_number']];
        }
        
        
    }
    
    //次卡支付
    public function secondpay($data){
        
        $room_id = $data['room_id'];//获取房间id
        
        if(!$room_id) return ['code'=>0,'msg'=>"参数错误"];
        $in_time = $data['in_time'];//获取入住时间
        if(!$in_time) return ['code'=>0,'msg'=>"请选择入住时间"];
        $out_time = $data['out_time'];//获取离店时间
        if(!$out_time) return ['code'=>0,'msg'=>"请选择离店时间"];
        $go_time = $data['go_time'];//获取离店时间
        if(!$go_time) return ['code'=>0,'msg'=>"请选择到店时间"];
        $days = $data['days'];//入住时长
        $userlist = json_decode($data['userlist'],true);//获取酒店身份登记信息
        if(empty($userlist)) return ['code'=>0,'msg'=>"请输入个人信息"];
        $invoice_id = $data['invoice_id'];//发票 
        $coupon_id = $data['coupon_id'];//优惠券id 
        $hours = $data['hour'];//住房的小时数针对钟点房
        $remark = $data['remark'];//备注
          
        //入住人数 
        $innum = count($userlist);
        
        if($innum>3){
            return ['code'=>0,'msg'=>"入住人数超过限制"];
        }
        
        //查找房间
        $room = db('room')->where(['id'=>$room_id,'status'=>0])->find();
        
        if(empty($room)) return ['code'=>0,'msg'=>"房间已下架"];
        



   
        // 转化时间格式 用来找到入住的每一天的时间
        $in_date = date('Y-m-d',$in_time);
        $out_date = date('Y-m-d',$out_time);
        $arr_date = db('time')->where(['date'=>['BETWEEN',[$in_date,$out_date]]])->select();

        if($room['one_cate'] == 0){
            // 为过夜房的时候需要将选择的最后一天减去 而钟点房不需要
            array_pop($arr_date);
        }
        // 获取id
        $arr_id = array_column($arr_date, 'id');
        // 查找这段时间内的房间信息
        $arr_prices = db('room_price')->where(['room_id'=>$room_id,'time_id'=>['IN',$arr_id],'status'=>0])->order('num asc')->select();
        // 查找房间的价格和这段范围内最低的数量
        // 最低的数量用min_num表示 顺便将一间房间在这段时间内的金额计算出来赋值给$room['new_price']
        $room['new_price'] = 0;
        $min_num = 100;
        foreach ($arr_prices as $i => $item) {
            $room['new_price'] += $item['price'];
            if($item['num'] != -1 && $item['num'] < $min_num){
                $min_num = $item['num'];
            }
        }
        if($innum>$min_num){
            return ['code'=>0,'msg'=>"房间数量不足,最多可预订".$min_num."套"];
        }
        
         
        $H = date('H');
        $time = time();
        //查找酒店设置的钟点房的信息
        $hotel = db('hotel')->field('start_time,end_time')->find(1);
        
        if ($room['one_cate'] == 1) { //钟点房
            if ($hotel['start_time'] > $H || $hotel['end_time'] < $H) {

                return ['code' => 0, 'msg' => "请在规定时间内预约"];
            }
            $cate = 1;
        }else{
            $cate = 0;
        }
        
        if($coupon_id!=0){
             
            return ['code' => 0, 'msg' => "该支付方式不支持优惠券"];
            
        }
        
        //计算次卡次数
        $card_num = $innum*$days;
        
        //查询用户的次卡
        $user = db('user')->where(['user_id'=>$this->user_id])->find();
       
        if ($user['second_num'] < $card_num) {
            return ['code' => 0, 'msg' => "次卡次数不足"];
        }
        
        //计算支付金额
        $allmoney = $room['new_price']*$innum*$days;
         
        if($allmoney<=0){
            return ['code' => 0, 'msg' => "支付金额错误"];
        }
         
        
        $data = [
            'order_number' => makeOrderNo(),
            'user_id' => $this->user_id,
            'room_id' => $room_id,
            'in_time' => $in_time, //入驻时间
            'out_time' => $out_time, //离店时间
            'go_time' => $go_time, //到店时间
            'days' => $days, //入驻天数
            'money' => $allmoney,
            'ordermoney' => $allmoney,
            'addtime' => time(), 
            'coupon_id' => $coupon_id, //优惠券id
            'type' => 1, //次卡支付
            'userlist' => serialize($userlist),
            'invoice_id' => $invoice_id, //发票id
            'remark' => $remark, //备注
            'room_num' => $innum, //人数
            'hours' => $hours, //小时数
            'status' => 1, //人数
            'paytime'=> time(),
            'cate' => $cate,
        ];
        
        db('room_price')->where(['time_id'=>['IN',$arr_id]])->setDec('num',$innum);
        db('room_price')->where(['time_id'=>['IN',$arr_id]])->setInc('use_num',$innum);
        $res = db('order')->insert($data);
        
        
        if ($res) {
            //操作 减去用户的次卡次数  减少房间的数量 增加房间的预定数量 发送模板消息
            db('user')->where(['user_id'=>$this->user_id])->setDec('second_num',$card_num);
                
            
            db('room')->where(['id'=>$room_id])->setInc('order_num',$innum);
            
              
            db('room')->where(['id'=>$room_id])->setDec('room_num',$innum);
             
            
            //用户消费记录表加数据
            moneyLog($this->user_id,$allmoney,2,0,$data['order_number'],"次卡预订房间",0,$card_num);
            
           
            
            //发送模板消息
            $this->send($data['order_number']);
            //获取手机号码
            $sendphone = $userlist[0]['phone'];
            $content = "你好";
            //发送短信
            // send_msg($sendphone,$content);
            
            return ['code' => 1, 'msg' => "支付成功", 'data' => $data['order_number']];
            
        } else {
            
            return ['code' => 1, 'msg' => "支付失败", 'data' => $data['order_number']];
            
        }
        
        
    }
    
    
   
    //余额购买房间
    public function rechargepay($data){
        
        $room_id = $data['room_id'];//获取房间id
       
        if(!$room_id) return ['code'=>0,'msg'=>"参数错误"];
        $in_time = $data['in_time'];//获取入住时间
        if(!$in_time) return ['code'=>0,'msg'=>"请选择入住时间"];
        $out_time = $data['out_time'];//获取离店时间
        if(!$out_time) return ['code'=>0,'msg'=>"请选择离店时间"];
        $go_time = $data['go_time'];//获取离店时间
        if(!$go_time) return ['code'=>0,'msg'=>"请选择到店时间"];
        
        
        
        $days = $data['days'];//入住时长
        $userlist = json_decode($data['userlist'],true);//获取酒店身份登记信息
        if(empty($userlist)) return ['code'=>0,'msg'=>"请输入个人信息"];
        $invoice_id = $data['invoice_id'];//发票 
        $coupon_id = $data['coupon_id'];//优惠券id 
        $hours = $data['hour'];//住房的小时数针对钟点房
        $remark = $data['remark'];//备注
        
       
        //入住人数 
        $innum = count($userlist);
       
        if($innum>3){
            return ['code'=>0,'msg'=>"入住人数超过限制"];
        }
        
       
        //查找房间
        $room = db('room')->where(['id'=>$room_id,'status'=>0])->find();
        
        if(empty($room)) return ['code'=>0,'msg'=>"房间已下架"];
        
        
        // 转化时间格式 用来找到入住的每一天的时间
        $in_date = date('Y-m-d',$in_time);
        $out_date = date('Y-m-d',$out_time);
        $arr_date = db('time')->where(['date'=>['BETWEEN',[$in_date,$out_date]]])->select();

        if($room['one_cate'] == 0){
            // 为过夜房的时候需要将选择的最后一天减去 而钟点房不需要
            array_pop($arr_date);
        }
        // 获取id
        $arr_id = array_column($arr_date, 'id');
        // 查找这段时间内的房间信息
        $arr_prices = db('room_price')->where(['room_id'=>$room_id,'time_id'=>['IN',$arr_id],'status'=>0])->order('num asc')->select();
        // 查找房间的价格和这段范围内最低的数量
        // 最低的数量用min_num表示 顺便将一间房间在这段时间内的金额计算出来赋值给$room['new_price']
        $room['new_price'] = 0;
        $min_num = 100;
        foreach ($arr_prices as $i => $item) {
            $room['new_price'] += $item['price'];
            if($item['num'] != -1 && $item['num'] < $min_num){
                $min_num = $item['num'];
            }
        }
        





        if($innum>$min_num){
            return ['code'=>0,'msg'=>"房间数量不足,最多可预订".$min_num."套"];
        }
        //计算支付金额
        $allmoney = $room['new_price']*$innum;
         
        if($allmoney<=0){
            return ['code' => 0, 'msg' => "支付金额错误"];
        }
        
        
        
        $user = db('user')
            ->where(['user_id' => $this->user_id])
            ->find();
        
        if ($user['money'] < $allmoney) {
            return ['code' => 0, 'msg' => "余额不足"];
        } 
         
        $H = date('H');
        $time = time();
        //查找酒店设置的钟点房的信息
        $hotel = db('hotel')->field('start_time,end_time')->find(1);
        
        if ($room['one_cate'] == 1) { //钟点房
            if ($hotel['start_time'] > $H || $hotel['end_time'] < $H) {

                return ['code' => 0, 'msg' => "请在规定时间内预约"];
            }
            $cate = 1;
        }else{
            $cate = 0;
        }
        
        
        
        if($coupon_id!=0){
             
            return ['code' => 0, 'msg' => "不支持优惠券"];
            
        }
        
        $data = [
            'order_number' => makeOrderNo(),
            'user_id' => $this->user_id,
            'room_id' => $room_id,
            'in_time' => $in_time, //入驻时间
            'out_time' => $out_time, //离店时间
            'go_time' => $go_time, //到店时间
            'days' => $days, //入驻天数
            'money' => $allmoney,
            'ordermoney' => $allmoney,
            'addtime' => time(), 
            'coupon_id' => $coupon_id, //优惠券id
            'type' => 2, //余额支付
            'userlist' => serialize($userlist),
            'invoice_id' => $invoice_id, //发票id
            'remark' => $remark, //备注
            'room_num' => $innum, //人数
            'hours' => $hours, //人数 
            'status' => 1, //人数
            'paytime'=> time(),
            'cate' => $cate,
        ];
        
        db('room_price')->where(['time_id'=>['IN',$arr_id]])->setDec('num',$innum);
        db('room_price')->where(['time_id'=>['IN',$arr_id]])->setInc('use_num',$innum);
        $res = db('order')->insert($data);
        
       
        if ($res) {
            //余额支付的操作  减少用户余额 减少房间的数量 增加房间的预定数量 发送模板消息
            db('user')->where(['user_id'=>$data['user_id']])->setDec('money',$allmoney);
               
            db('room')->where(['id'=>$room_id])->setDec('room_num',$innum);
              
            //用户消费记录表加数据
            moneyLog($this->user_id,$allmoney,3,0,$data['order_number'],"余额预订房间");
            
           
            
            //发送模板消息
            $this->send($data['order_number']);
            
            //获取手机号码
            $sendphone = $userlist[0]['phone'];
            
            $content = "你好，你已经支付成功了，请尽快携带行李入住！";
            //发送短信
            // send_msg($sendphone,$content);
            
            return ['code' => 1, 'msg' => "支付成功",'data'=>$data['order_number']];
        } else {
            return ['code' => 0, 'msg' => "支付失败"];
        }
        
        
    }
    
    
    /**
     * 生成房间订单
     */
    public function insertRoomOrder(){
        
        $data = input('post.');
        $type = input('type');
        
        //微信支付
        if($type==0){
            $wxpay = $this->wxpay($data);
            return $wxpay;
        }elseif($type==1){//次卡支付
            $secondpay = $this->secondpay($data);
            return json($secondpay);
        }elseif($type==2){//余额支付
           
            $rechargepay = $this->rechargepay($data);
            return json($rechargepay);
        }
              
    }
    /**
     * 
     * 根据订单号查询房间订单
     * 
     */
    public function getorderinfo(){
        if(request()->isPost()){
            $order_number = input('post.order_number');
            $order = db('order')->where(['order_number'=>$order_number])->find();
            return model('Res')->ctx($order);
        }else{
            return model('Res')->noPost();
        }
    }
    
    
    // 退款订单查询
    public function getinfo(){
        if(request()->isPost()){
            $order_number = input('post.order_number');
            $order = db('order')
                ->alias('o')
                ->join('room r','r.id=o.room_id')
                ->join('room_cate c','r.two_cate = c.id')
                ->where(['o.order_number'=>$order_number])
                ->field('order_number,order_id,c.title as title,description,money,logo,ordermoney')
                ->find()
            ;
            return model('Res')->ctx($order);
        }else{
            return model('Res')->noPost();
        }
    }
    // 取消次卡订单
    public function cancelsecondorder(){
        
        $order_id = input('id');
        if(!$order_id) return json(['code'=>0,'msg'=>"参数错误"]);
        $order = db('second_card_order')->where(['id'=>$order_id])->find();
        if(empty($order)) return json(['code'=>0,'msg'=>"订单不存在"]);
        if($order['status']!=0){
            db('second_card_order')->where(['id'=>$order_id])->update(['is_delete'=>1]);
        return json(['code'=>1,'msg'=>"订单删除成功"]);
        }else{
            db('second_card_order')->where(['id'=>$order_id])->delete();
            return json(['code'=>1,'msg'=>"订单取消成功"]);
        }
       
    }
    
    // 取消充值卡卡订单
    public function cancelrechargeorder(){
            
        $order_id = input('id');
        if(!$order_id) return json(['code'=>0,'msg'=>"参数错误"]);
        $order = db('recharge_card_order')->where(['id'=>$order_id])->find();
        if(empty($order)) return json(['code'=>0,'msg'=>"订单不存在"]);
        if($order['status']!=0){
            db('recharge_card_order')->where(['id'=>$order_id])->update(['is_delete'=>1]);
            return json(['code'=>1,'msg'=>"订单删除成功"]);
        }else{
            db('recharge_card_order')->where(['id'=>$order_id])->delete();
            return json(['code'=>1,'msg'=>"订单取消成功"]);
        }
        
    }

    
    
     //发送模板消
    public function send($out_trade_no)
    {
		//查询订单
		$order = db('order')->where(['order_number' => $out_trade_no])->find();
	    
		//查询用户
		$openid = db('user')->where(['user_id'=>$order['user_id']])->value('openid');
		//查询房间
		$title = db('room')
		    ->alias('a')
		    ->join('think_room_cate b','a.two_cate=b.id','left')
		    ->where(['a.id'=>$order['room_id']])
		    ->value('title');
		
		if($order['cate']==0){
		    $keytitle = $order['days']."天";
		}elseif($order['cate']==1){
		    $keytitle = $order['days']."小时";
		}
		
		$remark = db('smg_reply')->where(['id'=>1])->value('content');  
		
		$in_time = date('Y-m-d H:i:s',$order['in_time']);
		$url = request()->server("REQUEST_SCHEME") . "://" . $_SERVER['SERVER_NAME']."/mobile/orderman.html";
        $template = array(
            'touser' => $openid,
            'template_id' => "f9B8larZ6JgTQJ9XCO27CoJ9t-EEVZlF9Ez5bNX6-pQ", //这个是模版ID，获取方法自己看文档很详细。
            'url' => $url,
            'topcolor' => "#7B68EE",
            'data' => array(
                'first' => array('value' => "您好，您已支付成功", 'color' => "#000"),
                'keyword1' => array('value' => $title, 'color' => '#F70997'),
                'keyword2' => array('value' => $keytitle, 'color' => '#248d24'),
                'keyword3' => array('value' => $in_time, 'color' => '#248d24'),
                'keyword4' => array('value' => $out_trade_no, 'color' => '#248d24'),
                'remark'  => array('value' => $remark, 'color' => '#1784e8'),
            )
        );
        $this->sendMessage($template);
    }
    
    //发送模板消息
    public function sendMessage($template)
    {   
        $jdk = new Jdk_inc();
        
        //获取access_token
        $access_token = $jdk->getToken(); 
         
        $json_template = json_encode($template);
        $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $access_token;
        $res = $this->httpPost($url, $json_template);      //以post方式 向用户发送数据
        return $res;
    }
    
    //模板消息
    public function httpPost($url,$data) {
    	$curl = curl_init();
    	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    	curl_setopt($curl, CURLOPT_TIMEOUT, 500);
    	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    	curl_setopt($curl, CURLOPT_URL, $url);
    	curl_setopt($curl, CURLOPT_POST, true);
    	curl_setopt($curl, CURLOPT_POSTFIELDS,$data);
    	$res = curl_exec($curl);
    	curl_close($curl);
    	return $res;
    }
    
    public function refundinfo(){
        $order_id = input('order_id');
        $list = db('order')
            ->alias('o')
            ->join('room r','o.room_id = r.id')
            ->join('room_cate c','r.two_cate = c.id')
            ->where(['o.order_id'=>$order_id,'o.status'=>4])
            ->field('c.title as title,logo,o.money as money,r.description as description,check_reason')
            ->find();
        return model('Res')->ctx($list);
        
    }
}
